package com.zzb.projectfactory.framework.role.dao;

import com.zzb.projectfactory.framework.common.BaseDAO;
import com.zzb.projectfactory.framework.common.DaoException;
import com.zzb.projectfactory.framework.role.dao.jpa.UserRepository;
import com.zzb.projectfactory.framework.role.entity.User;
import com.zzb.projectfactory.framework.utils.Misc;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * 用户账号 Dao接口
 */
@Repository
public class UserDAO extends BaseDAO<User,UserRepository> {
    @Autowired
    private UserRepository userRepository;
    @Override
    public UserRepository getRepository() { return userRepository; }

    /**通过用户登录名查找符合的用户数量*/
    public long countUserByuserName(String name){
        return countBySpecification((root, criteriaQuery, criteriaBuilder) -> {
            criteriaQuery.where(criteriaBuilder.equal(root.get("userName").as(String.class),name));
            return criteriaQuery.getRestriction();
        });
    }

    /**通过用户名和密码查找查找*/
    public User getByUsernameAndPassword(String name,String password) throws DaoException {
        List<User> users = selectListBySpecification((root, criteriaQuery, criteriaBuilder) -> {
            Predicate userNamePredicate = criteriaBuilder.equal(root.get("username").as(String.class), name);
            Predicate passwordPredicate = criteriaBuilder.equal(root.get("password").as(String.class), Misc.generatePassword(password));
            criteriaQuery.where(criteriaBuilder.and(userNamePredicate, passwordPredicate));
            return criteriaQuery.getRestriction();
        });
        if(CollectionUtils.size(users) == 0){
            throw new DaoException("用户账号或密码错误");
        }
        else if(CollectionUtils.size(users) != 1){
            throw new DaoException("用户存在异常现象，请联系管理员吧");
        }
        return users.get(0);
    }
}
